package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.AreaInfo;
import com.maiji.cloud.entities.login.LoginLog;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.mapper.LoginLogMapper;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.login.UploadLocationReqDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.AppUserService;
import com.maiji.cloud.service.AreaInfoService;
import com.maiji.cloud.service.LoginLogService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.service.UserService;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.UUID_MD5;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Autowired
    private UserService userService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AreaInfoService areaInfoService;
    @Autowired
    private RedisTemplate<String, Object> maiji1RedisTemplate;

    @Override
    public BaseResDto uploadLocation(UploadLocationReqDto data, String maijiToken) {
        AppUser appUser = RedisUtil.getAppUserByRedis(maiji1RedisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, appUserService);
        AreaInfo areaInfo =new AreaInfo();
        if (StringUtil.isBlank(data.getProvince())) {
            LoginLog loginLog = selectOne(new EntityWrapper<LoginLog>().eq("user_id", appUser.getUuId()));
            if (loginLog != null) areaInfo = areaInfoService.selectById(loginLog.getAreaId());
        } else BeanUtils.copyProperties(data, areaInfo);
        areaInfo.setUuId(UUID_MD5.getUUID());
        if (! areaInfoService.insert(areaInfo)) return new BaseResDto(Status.ERROR);
        UserInfo userInfo = userService.selectOne(new EntityWrapper<UserInfo>().eq("user_id", appUser.getUuId()));
        if (StringUtil.isBlank(userInfo.getAreaId())) userService.updateById(userInfo.setAreaId(areaInfo.getUuId()));
        LoginLog loginLog = new LoginLog()
                .setUuId(UUID_MD5.getUUID())
                .setUserId(appUser.getUuId())
                .setLoginTime(new Date())
                .setAreaId(areaInfo.getUuId());
        if (! insert(loginLog)) return new BaseResDto(Status.ERROR);
        return new BaseResDto(Status.SUCCESS);
    }

}
